//
//  SetMessageViewController.m
//  Molian
//
//  Created by 小蚕科技 on 15/5/21.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

#import "SetMessageViewController.h"
#import "MessageTableViewCell.h"
@interface SetMessageViewController ()<UITableViewDataSource,UITableViewDelegate,MessageTableViewCellDelegate,UIPickerViewDataSource,UIPickerViewDelegate>
{
    NSArray *titleArr;
   
}
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *timerArr;
@property (nonatomic, strong)UIView *selectView;

@property (nonatomic, strong) NSString *beginTimer;
@property (nonatomic, strong) NSString *finishTimer;
@property (nonatomic, strong) UILabel *changeLabel;
@property (nonatomic, strong) NSMutableDictionary *switchDic;

@end

@implementation SetMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSUserDefaults *u =[NSUserDefaults standardUserDefaults];
    NSDictionary *dic = [u objectForKey: [NSString stringWithFormat:@"%@myswitchdic",[MLUser currentUser].objectId]];
    
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
   
    //通知NO,免打扰为NO,
    //notification,voice,shake,noDisturb
    self.switchDic = [NSMutableDictionary dictionaryWithDictionary:dic];
    
    self.beginTimer = @"00";
    self.finishTimer = @"00";
    self.title = @"消息设置";
    titleArr = @[@"消息通知显示详情",@"开启后显示详细内容",@"勿扰时段00:00-00:00",@"开启后,勿扰时段收到的消息不再提醒"];
    self.timerArr = @[@"00",@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20",@"21",@"22",@"23"];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight, DeviceWidth, DeviceHeight-kNavigationBarHeight)style:UITableViewStylePlain];
    self.tableView.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollsToTop = YES;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.tableFooterView = [[UIView alloc] init];//不显示空的cell
    [self.view addSubview:self.tableView];
    
    self.selectView = [[UIView alloc] initWithFrame:CGRectMake(15, DeviceHeight-180, DeviceWidth-30, 180)];
    UIButton *cancel = [UIButton buttonWithType:UIButtonTypeCustom];
    self.selectView.hidden = YES;
    [cancel setTitle:@"取消" forState:UIControlStateNormal];
    [cancel addTarget:self action:@selector(clickCancel) forControlEvents:UIControlEventTouchUpInside];
    cancel.frame = CGRectMake(0, 0, 60, 30);
    cancel.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [cancel setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.selectView addSubview:cancel];
    UIButton *confirm = [UIButton buttonWithType:UIButtonTypeCustom];
    [confirm setTitle:@"确定" forState:UIControlStateNormal];
    [confirm addTarget:self action:@selector(clickConfirm) forControlEvents:UIControlEventTouchUpInside];
    confirm.frame = CGRectMake(self.selectView.frame.size.width-60, 0, 60, 30);
    confirm.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
     [confirm setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.selectView addSubview:confirm];
    
  UIPickerView  *myPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 30, DeviceWidth-30, 150)];
    myPickerView.delegate = self;
    myPickerView.dataSource = self;
    [_selectView addSubview:myPickerView];
     [self.view addSubview:self.selectView];
    // Do any additional setup after loading the view.
}
- (void)clickConfirm
{
    _selectView.hidden = YES;
    
    [self setNotDisturb];
}
- (void)clickCancel
{
    _selectView.hidden = YES;
}
#pragma mark UIPickerView
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return self.timerArr.count;
}
//-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
//{
//    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth/2-45, 40)];
//    label.textAlignment = NSTextAlignmentCenter;
//    label.font = [UIFont fontWithName:FontName size:15];
//    label.text = [NSString stringWithFormat:@"%@:00",self.timerArr[row]];
//    return label;
//}
//返回指定列，行的高度，就是自定义行的高度
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return  40;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return  [NSString stringWithFormat:@"%@:00",self.timerArr[row]];
}
//监听轮子的移动
- (void)pickerView:(UIPickerView *)pickerView
      didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {
        self.beginTimer = self.timerArr[row];
    }else{
        self.finishTimer = self.timerArr[row];
    }
    self.changeLabel.text= [NSString stringWithFormat:@"勿扰时段%@:00-%@:00",self.beginTimer,self.finishTimer];
    
}
#pragma mark
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (section == 0) {
        return 1;
    }else if(section == 1){
        return 1;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // //通知NO,免打扰为NO
    //notification,voice,shake,noDisturb
    if (indexPath.section == 0||indexPath.section == 1) {
        MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[MessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        NSString *str;
        if (indexPath.section==0) {
            
            if (indexPath.row == 0) {
                str = [self.switchDic objectForKey:@"notification"];
            }
//            else if (indexPath.row ==1){
//                str = [self.switchDic objectForKey:@"voice"];
//            }else if(indexPath.row == 2){
//                str = [self.switchDic objectForKey:@"shake"];
//            }
           
            cell.textLabel.text = titleArr[indexPath.row];
             cell.myswitch.tag = 123+indexPath.row;
            
        }else{
            str = [self.switchDic objectForKey:@"noDisturb"];
            NSString *bengin = [self.switchDic objectForKey:@"beginTimer"];
            NSString *finish = [self.switchDic objectForKey:@"finishTimer"];
            if (bengin&&finish&&bengin.length&&finish.length) {
                self.finishTimer = bengin;
                self.beginTimer = finish;
                cell.textLabel.text = [NSString stringWithFormat:@"勿扰时段%@:00-%@:00",bengin,finish];
            }else{
                 cell.textLabel.text = titleArr[2];
            }
            //self.finishTimer
            //self.beginTimer
            self.changeLabel = cell.textLabel;
             cell.myswitch.tag = 123+4;
        }
       
         [self NSString:str cell:cell];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        return cell;
    }else{
        return nil;
    }
}
- (void)NSString:(NSString *)str cell:(MessageTableViewCell *)cell
{
    if (str&&[str isEqualToString:@"YES"]) {
        cell.myswitch.on = YES;
    }else{
        cell.myswitch.on = NO;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     _selectView.hidden = YES;
}
- (void)clickSwitch:(UISwitch *)s
{//通知,声音,震动默认为NO,免打扰为NO,
    //notification,voice,shake,noDisturb
    
    
    //存储设置信息 //并把对应信息存入  self.switchDic
    switch (s.tag) {
        case 123:
            //新消息通知
            [self notificationDetail:s.on];
            
            break;
//        case 124:
//            if (s.on) {
//                
//            }else{
//                
//            }
//            //声音
//            break;
//        case 125:
//            if (s.on) {
//                
//            }else{
//                
//            }
//            //震动
//            break;
        case 127:
            if (s.on) {
                _selectView.hidden = NO;
                
            }else{
                //关闭免打扰
                [self changeNotDisturb];
                _selectView.hidden = YES;
            }
            //勿扰时段
            break;
            
        default:
            break;
    }
    [self saveSwitchDic];
    
}
- (void)saveSwitchDic
{
    NSUserDefaults *u = [NSUserDefaults standardUserDefaults];
    [u setObject:self.switchDic forKey: [NSString stringWithFormat:@"%@myswitchdic",[MLUser currentUser].objectId]];
    [u synchronize];
}
- (void)notificationDetail:(BOOL)is
{
   
    EMPushNotificationOptions *p = [[EMPushNotificationOptions alloc] init];
    p.nickname = [MLUser currentUser].nickname;
    if (is) {
        p.displayStyle = ePushNotificationDisplayStyle_messageSummary;
    }else{
        p.displayStyle = ePushNotificationDisplayStyle_simpleBanner;
    }
    
    [[EaseMob sharedInstance].chatManager asyncUpdatePushOptions:p completion:^(EMPushNotificationOptions *options, EMError *error) {
        if(!error){
           // [HUD Prompt:@"设置成功"];
            if(is){
                [self.switchDic setObject:@"YES" forKey:@"notification"];
            }else{
                 [self.switchDic setObject:@"NO" forKey:@"notification"];
            }
            [self saveSwitchDic];
        }else{
            [HUD Prompt:@"设置失败,返回重试"];
            
        }
    } onQueue:nil];
}
- (void)changeNotDisturb
{
    EMPushNotificationOptions *p = [[EMPushNotificationOptions alloc] init];
    p.nickname = [MLUser currentUser].nickname;
    p.noDisturbStatus = ePushNotificationNoDisturbStatusClose;//关闭免打扰
    [[EaseMob sharedInstance].chatManager asyncUpdatePushOptions:p completion:^(EMPushNotificationOptions *options, EMError *error) {
        if(!error){
            [self.switchDic setObject:@"NO" forKey:@"noDisturb"];
            [self saveSwitchDic];
        }else{
            [HUD Prompt:@"设置失败,返回重试"];

        }
    } onQueue:nil];
}
- (void)setNotDisturb
{
    EMPushNotificationOptions *p = [[EMPushNotificationOptions alloc] init];
    p.nickname = [MLUser currentUser].nickname;
    p.noDisturbStatus = ePushNotificationNoDisturbStatusCustom;//自定义免打扰
    p.noDisturbingStartH = [self.beginTimer integerValue];
    p.noDisturbingEndH = [self.finishTimer integerValue];
    [[EaseMob sharedInstance].chatManager asyncUpdatePushOptions:p completion:^(EMPushNotificationOptions *options, EMError *error) {
        if(!error){
          //  [HUD Prompt:@"设置成功"];
             [self.switchDic setObject:self.beginTimer forKey:@"beginTimer"];
             [self.switchDic setObject:self.finishTimer forKey:@"finishTimer"];
            [self.switchDic setObject:@"YES" forKey:@"noDisturb"];
            [self saveSwitchDic];
        }else{
            [HUD Prompt:@"设置失败,返回重试"];
        }
    } onQueue:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, 44)];
       header.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    
    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, DeviceWidth-20, 44)];
    textLabel.textColor = [UIColor grayColor];
    if (section == 1) {
        textLabel.text = titleArr[1];
    }else if (section == 2){
        textLabel.text = titleArr[3];
    }else{
        textLabel.text = @"";
    }
    textLabel.font = [UIFont fontWithName:FontName size:11];
    textLabel.adjustsFontSizeToFitWidth = YES;
    [header addSubview:textLabel];
    return header;
}
- (CGFloat )tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 10;
    }else if (section ==1||section == 2){
        return 44;
    }else {
        return 0;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
